#系统用户
common_util = require('../services/common_util')
SysRole = require('./sys_role').SysRole
SysResource = require('./sys_resource').SysResoure
config = require('../config')
Schema = config.Schema
mongoose = config.mongoose

SysUserSchema = new Schema({
  username:
    type:String
    index:true
  real_name:String
  password:String
  create_date:Date
  roles:[String]
  categorys:[String]
})

module.exports.SysUser = mongoose.model 'sys_user',SysUserSchema
SysUser = mongoose.model 'sys_user'


#保存
exports.save = (req,callback) ->
  roles = []
  roles.push req.param("role_id")
  sysUser = new SysUser({
    username:common_util.trim(req.param("username"))
    real_name:req.param("real_name")
    password:req.param("password")
    create_date: new Date()
    roles:roles
  })
  sysUser.save (err) ->
    if(err)
      callback(err)
    else
      callback(null)


#根据用户名判断用户是否已存在
exports.isUsernameExist = (username,callback) ->
  SysUser.count {username:username},(err,count) ->
    if err
      callback(err)
    else
      callback(null,count)


#判断用户是否已拥有某角色
exports.isUsernameIncludeRole = (username,role_id,callback) ->
  params = {}
  roles = []
  roles.push role_id
  params.username = username
  params.roles = {'$in':roles}
  SysUser.count params,(err,count) ->
    if err
      callback(err)
    else
      callback(null,count)

#根据用户名称查询出用户的权限,返回0未获授权
exports.findUserRoleByUsername = (username,callback) ->
  conditions = {"username":username}
  SysUser.findOne conditions,(err,user) ->
    if err
      console.error(err)
      callback err
    else
      if !user
        callback "0"
      else
        SysRole.find {"_id":{"$in":user.roles}},(err,roles) ->
          if err
            console.error(err)
            callback err
          else
            if !roles
              callback "0"
            else
              resources = []
              urls = []
              SysResource.find (err,resourceList) ->
                if err
                  console.error(err)
                  callback err
                else
                  for role in roles
                    for r in role.resources
                      if !(r.res_id.toString() in resources)
                        resources.push r.res_id.toString()
                  for r1 in resources
                    for r2 in resourceList
                      if r1 == r2._id.toString()
                        urls.push {"res_id":r2._id,"res_name":r2.res_name,"url":r2.url,"http_method":r2.http_method}
                  callback null,urls

